package cn.com.KnowNews.dao.daoImpl;

import cn.com.KnowNews.dao.ICategoryDao;
import cn.com.KnowNews.entity.Category;
import cn.com.KnowNews.utils.DBConn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class CategoryDaoImpl implements ICategoryDao {
    private Connection conn;
    private PreparedStatement ps;

    @Override
    public List<Category> showCategory() throws Exception {

        conn= DBConn.getConnection();
        String sql="select * from t_category";

        List<Category> categoryList = new ArrayList<Category>();
        ps=conn.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();

        while(resultSet.next()){

            Category category = new Category();

            category.setId(resultSet.getInt("id"));
            category.setCategory(resultSet.getString("category"));
            category.setAdder(resultSet.getString("adder"));
            categoryList.add(category);
        }
        DBConn.release(resultSet,ps,conn);
        return categoryList;
    }

    @Override
    public int delCate(int id) throws Exception {
        conn=DBConn.getConnection();
        String sql = "delete from t_category where id = ?";
        ps=conn.prepareStatement(sql);
        ps.setInt(1,id);
        int result = ps.executeUpdate();
        DBConn.release(ps,conn);
        return result;
    }

    @Override
    public int addCate(String cate, String adder) throws Exception {
        conn=DBConn.getConnection();
        String sql = "insert into t_category (category,adder) values (?,?)";
        ps=conn.prepareStatement(sql);
        ps.setString(1,cate);
        ps.setString(2,adder);
        int result = ps.executeUpdate();
        DBConn.release(ps,conn);
        return result;
    }
}
